﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WebScraperLibrary
{
    public class TvNuParser
    {
        public TvNuParser()
        {

        }

        public List<Channel> GetChannels(string data)
        {
            var htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(data);

            var listItems = htmlDoc.DocumentNode.SelectNodes(@"//div[@class='tabla_topic']");
            var channelList = new List<Channel>();

            foreach (var item in listItems)
            {
                var channel = new Channel();
                if (item.SelectSingleNode("a").Attributes["href"].Value != null)
                {
                    channel.Link = item.SelectSingleNode("a").Attributes["href"].Value;
                }
                if (item.SelectSingleNode(@"p/a") != null)
                {
                    channel.Name = item.SelectSingleNode(@"p/a").InnerText;
                }
                channelList.Add(channel);
            }

            return channelList;
        } 

        public string GetProgramsData(string data)
        {
            var htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(data);

            var listItems = htmlDoc.DocumentNode.SelectNodes(@"//div[@class='program']/div");
            string retval = "";

            if(listItems != null)
            foreach (string listItem in listItems.Select(li => li.OuterHtml))
            {
                retval += listItem + "\r\n";
            }

            return retval;
        }

        public List<TvProgram> GetTimeAndShow(string ProgramsData)
        {
            var htmlDoc = new HtmlAgilityPack.HtmlDocument();
            htmlDoc.LoadHtml(ProgramsData);
            var listItems = htmlDoc.DocumentNode.SelectNodes(@"div");
            var retval = new List<TvProgram>();

            if(listItems != null)
            foreach (var item in listItems)
            {
                var tvProg = new TvProgram();

                if (item.Id != null)
                {
                    tvProg.Time = item.Id;
                }
                if (item.SelectSingleNode(@"h2/strong") != null)
                {
                    tvProg.Name = item.SelectSingleNode(@"h2/strong").InnerText;
                }
                if (item.SelectSingleNode(@"p") != null)
                {
                    tvProg.Desc = item.SelectSingleNode(@"p").InnerText;
                }
                if (item.SelectSingleNode(@"img") != null)
                {
                    tvProg.ImgUrl = item.SelectSingleNode(@"img").Attributes["src"].Value;
                }
                retval.Add(tvProg);
            }
            return retval;
        }
    }
}
